const { Model, DataTypes } = require('sequelize');
const sequelize = require('../db/db');
const User = require('./User');

/**
 * 实时对战房间模型
 */
class BattleRoom extends Model { }
BattleRoom.init(
  {
    id: {
      type: DataTypes.STRING(18),
      primaryKey: true,
      allowNull: false,
      comment: '房间ID'
    },
    creator_id: {
      type: DataTypes.STRING(18),
      allowNull: false,
      comment: '创建者ID'
    },
    opponent_id: {
      type: DataTypes.STRING(18),
      allowNull: true,
      comment: '对手ID'
    },
    status: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '房间状态：0-等待匹配，1-对战中，2-已结束'
    },
    question_list: {
      type: DataTypes.JSON,
      allowNull: false,
      comment: '题目ID列表'
    },
    start_time: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: '开始时间'
    },
    end_time: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: '结束时间'
    },
    winner_id: {
      type: DataTypes.STRING(18),
      comment: '胜者ID（平局为NULL）'
    },
    is_draw: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      comment: '是否平局' //0false 1true 0不平局，1平局
    },
    creator_user_score: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '创建者得分'
    },
    opponent_user_score: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '对手得分'
    },
    create_time: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
      comment: '创建时间'
    }
  },
  {
    sequelize,
    modelName: 'BattleRoom',
    tableName: 'battle_room',
    timestamps: false,
    comment: '对战房间表'
  }
);

// 建立与User表的关联
BattleRoom.belongsTo(User, {
  foreignKey: 'creator_id',
  as: 'creator'
});

BattleRoom.belongsTo(User, {
  foreignKey: 'opponent_id',
  as: 'opponent'
});

module.exports = BattleRoom;